package com.whc.orders.controller;


import com.whc.api.dto.OrderAndGoodsDto;
import com.whc.api.dto.OrderDto;
import com.whc.common.context.BaseContext;
import com.whc.orders.domain.entity.Orders;
import com.whc.orders.domain.vo.OrdersVo;
import com.whc.orders.service.OrdersService;
import com.whc.common.domain.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


@RestController
@Api(tags = "订单接口")
@RequestMapping("/client/order")
@Slf4j
public class OrdersController {
    @Autowired
    private OrdersService ordersService;

    @ApiOperation("添加订单")
    @PostMapping("/addOrders")
    public Result addOrders(@RequestBody OrderDto orderDto){
        Long orderNumber = ordersService.addOrder(orderDto);
        return Result.success(orderNumber);
    }

    @ApiOperation("修改订单为已支付")
    @PutMapping("/toPayOrders")
    public Result toPayOrders(@RequestParam("orderNumber") Long orderNumber){
        ordersService.toPayOrder(orderNumber);
        return Result.success();
    }

    @ApiOperation("查询历史订单")
    @GetMapping("/selectOrders")
    public Result<List<OrdersVo>> selectUserAll(){
        Long currentId = BaseContext.getCurrentId();
        if(currentId==null){
            return Result.error("用户未登录");
        }
        List<Orders> orders = ordersService.selectUserAll(currentId);
        ArrayList<OrdersVo> res=new ArrayList<>();
        for(Orders o:orders){
            OrdersVo ordersVo = new OrdersVo();
            BeanUtils.copyProperties(o,ordersVo);
            res.add(ordersVo);
        }
        return Result.success(res);
    }

    @ApiOperation("取消订单")
    @PostMapping("/cancleOrder")
    public Result cancleOrder(@RequestParam("orderNumber") Long orderNumber){
        ordersService.cancelOrder(orderNumber);
        return Result.success();
    }

    @ApiOperation("根据订单编号查询相关物品")
    @GetMapping("/selectGoodsByOrderNumber")
    public Result<List<OrderAndGoodsDto>> selectGoodsByOrderNumber(@RequestParam("orderNumber") Long orderNumber){
        List<OrderAndGoodsDto> orderAndGoodsDtos = ordersService.selectGoodsByOrderNumber(orderNumber);
        return Result.success(orderAndGoodsDtos);
    }

    @ApiOperation("查询所有订单")
    @GetMapping("selectAll")
    public Result<List<OrdersVo>> selectAll(){
        List<Orders> orders = ordersService.selectAll();
        ArrayList<OrdersVo> res=new ArrayList<>();
        for(Orders o:orders){
            OrdersVo ordersVo = new OrdersVo();
            BeanUtils.copyProperties(o,ordersVo);
            res.add(ordersVo);
        }
        return Result.success(res);
    }

}
